package org.practice.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.practice.model.Book;
import org.practice.util.DaoException;
import org.practice.util.HibernateSessionFactory;

public class BookDaoImpl implements BookDao{
	private Map<Integer,String> queryList=new HashMap<Integer,String>();
	private static Logger logger=Logger.getLogger(BookDaoImpl.class);
	public BookDaoImpl(){
		initOrderOptions();
	}
	public void initOrderOptions(){
		queryList.put(BookDao.ORDER_DEFAULT, "from Book b where b.categoryId=?");
		queryList.put(ORDER_NAME_ASC, "from Book b where b.categoryId=? order by b.name asc");
		queryList.put(ORDER_NAME_DESC, "from Book b where b.categoryId=? order by b.name desc");
		
	}
	

	@Override
	public List<Book> findBookByCategoryId(Integer categoryId,
			int page, int rowsPerPage, Integer orderBy) throws DaoException {
		Session session=null;
		Transaction tr=null;
		List<Book> allBooks=null;
		try {
			session=HibernateSessionFactory.openSession();
			tr=session.beginTransaction();
			Query query=session.createQuery(queryList.get(orderBy));
			query.setInteger(0, categoryId);
			query.setMaxResults(rowsPerPage);
			query.setFirstResult((page-1)*rowsPerPage);
			allBooks=query.list();
			tr.commit();
		} catch (HibernateException e) {
			tr.rollback();
			logger.error("��ݷ��ʴ���",e);
			throw new DaoException("��ݷ��ʳ���",e);
		} finally{
			HibernateSessionFactory.closeSession();
		}
		return allBooks;
		
	}
	
	@Override
	public int getTotalPagesByCategoryId(Integer categoryId, int rowsPerPage)
			throws DaoException {
		Session session=null;
		Transaction tr=null;
		int totalPages=0;
		try {
			session=HibernateSessionFactory.openSession();
			tr=session.beginTransaction();
			Query query=session.createQuery("select count(*) from Book b where b.categoryId=?");
			query.setInteger(0, categoryId);
//			query.setParameter(0, categoryId);
			List<Long> list=query.list();
			int totalRows=list.get(0).intValue();
			if (totalRows % rowsPerPage == 0) {
				totalPages=totalRows / rowsPerPage;
			} else {
				totalPages=totalRows / rowsPerPage + 1;
			}
			tr.commit();
		} catch (HibernateException e) {
			tr.rollback();
			logger.error("��ݷ��ʳ���",e);
			throw new DaoException("��ݷ��ʳ���",e);
		} finally{
			HibernateSessionFactory.closeSession();
		}
		return totalPages;
	}

	@Override
	public Map<Integer, String> getOrderOptions() {
		Map<Integer, String> map = new TreeMap<Integer, String>();
		map.put(ORDER_DEFAULT, "book.order.default");
		map.put(BookDao.ORDER_NAME_ASC, "book.order.name.asc");
		map.put(ORDER_NAME_DESC, "book.order.name.desc");
		return map;
	}

}
